package net.csdn.business.notify.handler.action;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.notify.common.model.entity.NotifyPrivateLetter;
import net.csdn.business.notify.common.pipeline.BusinessProcess;
import net.csdn.business.notify.common.pipeline.ProcessContext;
import net.csdn.business.notify.common.pipeline.domain.PrivateTaskInfo;
import net.csdn.business.notify.handler.service.INotifyPrivateLetterService;
import net.csdn.business.notify.common.utils.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * @ClassName SavePrivateAction
 * @Description 保存私信记录到私信表中
 * @Author zhangyl
 * @Date 2023/12/5 18:20 
 */
@Slf4j
@Service
public class SavePrivateAction implements BusinessProcess<PrivateTaskInfo> {


    @Autowired
    private INotifyPrivateLetterService privateLetterService;

    @Override
    public void process(ProcessContext<PrivateTaskInfo> context) {
        PrivateTaskInfo taskInfo = context.getProcessModel();
        Set<String> receivers=taskInfo.getReceiver();
        String batchNum=taskInfo.getBatchNum();
        String senderId=taskInfo.getSenderId();
        Long startTime=taskInfo.getStartTime();
        //批量查询用户信息，并记录到数据库
        if (receivers!=null&&receivers.size()>0){
            //批量保存当前批次通知记录
            List<NotifyPrivateLetter> records=new ArrayList<>();
            for (String receiverId:receivers){
                //屏蔽自己给自己发送通知或私信
                if(StringUtils.isBlank(receiverId)||receiverId.equals(senderId)){
                    continue;
                }
                //当用户存在时,组装用户通知记录信息，批量保存入库
                NotifyPrivateLetter privateRecord=new NotifyPrivateLetter();
                privateRecord.setObjectId(IdUtil.fastSimpleUUID());
                privateRecord.setReceiverId(receiverId);
                privateRecord.setSenderId(senderId);
                String dialogueId=StrUtils.genDialogueId(senderId,receiverId);
                privateRecord.setDialogueId(dialogueId);
                privateRecord.setBatchNum(batchNum);
                privateRecord.setContent(taskInfo.getContent());
                privateRecord.setCreatedDate(taskInfo.getSendDate());
                privateRecord.setIsSystem(false);
                records.add(privateRecord);
            }
            if(records.size()>0){
                privateLetterService.insertBatch(records);
            }
        }
        Long endTime=System.currentTimeMillis();
        log.info("private message batchnum:{} process time is: {}ms",batchNum,endTime-startTime);
    }
}
